#!/usr/bin/env python3  /*设定脚本文件直接能执行*/
# -*- coding:utf-8 -*-   /*设置编码*/
"""
@Author: WANDERSON M.PIMENTA
@Software: PyCharm 、Qt Designer and PySide6
@File: tQToggleSwitch.py
@Time: 2024/05/11 16:35
@Function：ctQToggleSwitch：自定义的切换开关
"""
from tQQtCore import *


# toggle switch
class ctQToggleSwitch(QCheckBox):
    def __init__(self,
                 width=50,
                 bg_color="#777",
                 circle_color="#DDD",
                 active_color="#00BCFF",
                 animation_curve=QEasingCurve.OutBounce):
        QCheckBox.__init__(self)
        # 设置固定大小
        self.setFixedSize(width, 28)
        self.setCursor(Qt.PointingHandCursor)

        # 设置颜色
        self._bg_color = bg_color
        self._circle_color = circle_color
        self._active_color = active_color

        self._position = 3
        self.__m_animation = QPropertyAnimation(self, b"position")
        self.__m_animation.setEasingCurve(animation_curve)
        self.__m_animation.setDuration(500)
        self.stateChanged.connect(self.__f_startAndStopAnimation)

    @Property(float)
    def position(self):
        return self._position

    @position.setter
    def position(self, pos):
        self._position = pos
        self.update()

    # 开始停止动画
    def __f_startAndStopAnimation(self, value):
        self.__m_animation.stop()
        if value:
            self.__m_animation.setEndValue(self.width() - 26)
        else:
            self.__m_animation.setEndValue(4)
        self.__m_animation.start()

    # 重写hitButton事件
    def hitButton(self, pos: QPoint):
        return self.contentsRect().contains(pos)

    # 重写paintEvent事件
    def paintEvent(self, e):
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)
        p.setFont(QFont("Segoe UI", 9))

        # 设置画笔
        p.setPen(Qt.NoPen)

        # 画矩形
        rect = QRect(0, 0, self.width(), self.height())

        if not self.isChecked():
            p.setBrush(QColor(self._bg_color))
            p.drawRoundedRect(0, 0, rect.width(), 28, 14, 14)
            p.setBrush(QColor(self._circle_color))
            p.drawEllipse(self._position, 3, 22, 22)
        else:
            p.setBrush(QColor(self._active_color))
            p.drawRoundedRect(0, 0, rect.width(), 28, 14, 14)
            p.setBrush(QColor(self._circle_color))
            p.drawEllipse(self._position, 3, 22, 22)

        p.end()
